//
//  MyTabInfoTableViewCell.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2020/9/10.
//  Copyright © 2020 moon. All rights reserved.
//

#import "MyTabInfoTableViewCell.h"

@interface MyTabBarItemCollectionViewCell : MKUITabBarItemCollectionViewCell
@property(nonatomic,strong) UIImageView *selectedBgView;
@property(nonatomic,strong) UIImageView *unselectedBgView;
@end
@implementation MyTabBarItemCollectionViewCell
- (CGRect)itemIndicatorRect{
    return CGRectZero;
}
- (id)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        self.clipsToBounds = NO;
        self.contentView.clipsToBounds = NO;
        
        self.selectedBgView = [[UIImageView alloc] initWithFrame:frame];
//        self.selectedBgView.layer.borderColor = [UIColor redColor].CGColor;
//        self.selectedBgView.layer.borderWidth = 1;
        self.selectedBgView.contentMode = UIViewContentModeScaleToFill;
        [self.contentView addSubview:self.selectedBgView];
        [self.contentView sendSubviewToBack:self.selectedBgView];
        
        self.unselectedBgView = [[UIImageView alloc] initWithFrame:frame];
        self.unselectedBgView.contentMode = UIViewContentModeScaleToFill;
        [self.contentView addSubview:self.unselectedBgView];
        [self.contentView sendSubviewToBack:self.unselectedBgView];
    }
    return self;
}
- (BOOL)isFirstCell{
    return self.collectionCellModel.indexInSectionModel==0;
}
- (BOOL)isLastCell{
    return self.collectionCellModel.indexInSectionModel==self.collectionCellModel.sectionModel.numberOfCells-1;
}
- (BOOL)isOnlyOneCell{
    return self.collectionCellModel.collectionModel.numberOfCells==1;
}
- (void)customLayoutSubviews{
    [super customLayoutSubviews];
    CGRect bounds = self.contentView.bounds;
    UIEdgeInsets imageCapInsets = self.class.imageCapInsets;
    {
        UIEdgeInsets inset1 = UIEdgeInsetsZero;;
        //
        if(self.isOnlyOneCell){
        }else if(self.isFirstCell){
            inset1.right = -imageCapInsets.right;
        }else if(self.isLastCell){
            inset1.left = -imageCapInsets.left;
        }else{
            inset1.right = -imageCapInsets.right;
            inset1.left = -imageCapInsets.left;
        }
        CGRect f1 = UIEdgeInsetsInsetRect(bounds, inset1);
        self.selectedBgView.frame = f1;
    }
    {
        UIEdgeInsets inset1 = UIEdgeInsetsMake(5, -1, 0, -1);//左右超出1px显示区域，防止出现因浮点精度导致相邻cell显示一条分割线
        CGRect f1 = UIEdgeInsetsInsetRect(bounds, inset1);
        self.unselectedBgView.frame = f1;
    }
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCellModel:(__kindof MKUICollectionViewCellModel *)cellModel{
    if(self.collectionCellModel.selected){
        [self.superview bringSubviewToFront:self];
    }else{
        [self.superview sendSubviewToBack:self];
    }
}
+ (UIEdgeInsets)imageCapInsets{//返回图片不可伸缩的四个角落尺寸.该尺寸是scale之后的值
    CGFloat imageScale = 3;//资源图片的@x倍数
    return UIEdgeInsetsMake(23./imageScale, 78./imageScale, 49./imageScale, 74./imageScale);
}
//图片使用单例，优化性能
#define DEF_icon_tab_bg(name,insets) + (UIImage *)name{\
    static UIImage *__share = nil;\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        __share = [[UIImage imageNamed:@#name] resizableImageWithCapInsets:(insets) resizingMode:(UIImageResizingModeStretch)];\
    });\
    return __share;\
}
DEF_icon_tab_bg(icon_tab_select_bg_onlyone,self.imageCapInsets)

DEF_icon_tab_bg(icon_tab_select_bg_first,self.imageCapInsets)
DEF_icon_tab_bg(icon_tab_unselect_bg_first,self.imageCapInsets)

DEF_icon_tab_bg(icon_tab_select_bg_last,self.imageCapInsets)
DEF_icon_tab_bg(icon_tab_unselect_bg_last,self.imageCapInsets)

DEF_icon_tab_bg(icon_tab_select_bg_center,self.imageCapInsets)
DEF_icon_tab_bg(icon_tab_unselect_bg_center,self.imageCapInsets)

- (void)customReloadCellModel{
    [super customReloadCellModel];
    if(self.isOnlyOneCell){
        self.selectedBgView.image = self.class.icon_tab_select_bg_onlyone;
        self.unselectedBgView.image = nil;
    }else if(self.isFirstCell){
        self.selectedBgView.image = self.class.icon_tab_select_bg_first;
        self.unselectedBgView.image = self.class.icon_tab_unselect_bg_first;
    }else if(self.isLastCell){
        self.selectedBgView.image = self.class.icon_tab_select_bg_last;
        self.unselectedBgView.image = self.class.icon_tab_unselect_bg_last;
    }else{
        self.selectedBgView.image = self.class.icon_tab_select_bg_center;
        self.unselectedBgView.image = self.class.icon_tab_unselect_bg_center;
    }
    self.selectedBgView.hidden = !self.collectionCellModel.selected;
    self.unselectedBgView.hidden = !self.selectedBgView.hidden;
}
- (CGSize)customSizeThatFits:(CGSize)size{
    return [super customSizeThatFits:size];
}
- (void)dealloc{
    
}

@end

@interface MyUITabBarItemViewContainerCollectionView : MKUITabBarItemViewContainerCollectionView
@end
@implementation MyUITabBarItemViewContainerCollectionView
- (id)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        self.itemCollectionCellClass = [MyTabBarItemCollectionViewCell class];
        [self.itemIndicatorView.superview sendSubviewToBack:self.itemIndicatorView];
        self.collectionView.clipsToBounds = NO;
        self.clipsToBounds = NO;
    }
    return self;
}
- (void)colorTraitCollectionDidChange{
    self.collectionView.backgroundColor = [UIColor clearColor];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGRect bounds = self.bounds;
    CGRect r = bounds;
    r.size.width = bounds.size.width/self.items.count;
    return r.size;
}
@end

@implementation MyTabInfoTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        //
        self.tab1 = [[MyTabInfoViewTableView alloc] init];
        self.tab2 = [[MyTabInfoViewCollectionView alloc] init];
        self.tab3 = [[MyTabInfoViewTableView alloc] init];
        //
        self.tabController = [[MKUITabBarController alloc] initWithItemContainerClass:[MyUITabBarItemViewContainerCollectionView class] contentContainerClass:[MKUITabBarContentContainerScrollView class]];
        
        self.tabController.delegate = self;
        [self.cellContentView addSubview:self.tabController.itemContainer];
        [self.cellContentView addSubview:self.tabController.contentContainer];
        self.tabController.contents =
        @[
            self.tab1,
            self.tab2,
            self.tab3,
        ];
        MKUILayoutConstraintItemWrapper *w1 = [MKUILayoutConstraintItemWrapper wrapItem:self.tabController.itemContainer sizeThatFitsBlock:^CGSize(MKUILayoutConstraintItemWrapper * _Nonnull wrapper, CGSize size, BOOL resizeItems) {
            UIView *itemContainer = wrapper.originItem;
            CGSize s = [itemContainer sizeThatFits:size];
            s.width = size.width;
            return s;
        }];
        [self.tabController reloadData];
        //
        self.expendButton = [[MKUIFlowLayoutButton alloc] init];
        self.expendButton.contentInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [self.expendButton setTitle:@"v" forState:UIControlStateNormal];
        [self.expendButton setTitle:@"^" forState:UIControlStateSelected];
        [self.expendButton addTarget:self action:@selector(__onExpendButtonDidTap:) forControlEvents:UIControlEventTouchUpInside];
        MKUILayoutConstraintItemWrapper *w2 = [MKUILayoutConstraintItemWrapper wrapItem:self.expendButton sizeThatFitsBlock:^CGSize(MKUILayoutConstraintItemWrapper * _Nonnull wrapper, CGSize size, BOOL resizeItems) {
            return CGSizeMake(size.width, 44);
        }];
        [self.cellContentView addSubview:self.expendButton];
        [self colorTraitCollectionDidChange];
        //
        self.flowlayout = [[MKUIFlowLayoutConstraint alloc] initWithItems:@[w1,self.tabController.contentContainer,w2] constraintParam:(MKUIFlowLayoutConstraintParam_V_T_C) contentInsets:UIEdgeInsetsMake(10, 0, 0, 0) interitemSpacing:0];
    }
    return self;
}
- (void)customLayoutSubviews{
    [super customLayoutSubviews];
    CGRect bounds = self.cellContentView.bounds;
    self.flowlayout.bounds = bounds;
    [self.flowlayout layoutItemsWithResizeItems:YES];
    [self.tabController reloadData];
}
- (void)colorTraitCollectionDidChange{
    [super colorTraitCollectionDidChange];
    [self.expendButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
    self.expendButton.backgroundColor = [UIColor whiteColor];
    self.tabController.contentContainer.backgroundColor = [UIColor whiteColor];
}
- (void)__onExpendButtonDidTap:(UIButton *)button{
    self.cellModel[@"expend"] = @(![self.cellModel mk_boolForKeyPath:@"expend" otherwise:NO]);
    [self.cellModel refreshWithAnimated:YES];
}
- (void)tabBarController:(MKUITabBarController *)controller didSelectIndex:(NSInteger)index{
    NSLog(@"tabBarControllerDidSelect:%ld",index);
    if([self.cellModel mk_integerForKeyPath:@"selectedTab"]!=index){
        self.cellModel[@"selectedTab"] = @(index);
        [self.cellModel refreshWithAnimated:YES];
    }
}
- (void)customReloadCellModel{
    [super customReloadCellModel];
    //
    self.expendButton.selected = [self.cellModel mk_boolForKeyPath:@"expend"];
    //
    self.tab1.cellModel = self.cellModel;
    [self.tab1 reloadData];
    
    self.tab2.cellModel = self.cellModel;
    [self.tab2 reloadData];
    
    //
    self.tab3.cellModel = self.cellModel;
    [self.tab3 reloadData];
    
    self.tabController.contentContainer.hidden = ![self.cellModel mk_boolForKeyPath:@"expend"];
    self.tabController.selectedIndex = [self.cellModel mk_integerForKeyPath:@"selectedTab"];
    [self.tabController reloadData];
    //
}
- (CGSize)customSizeThatFits:(CGSize)size{
    UIEdgeInsets insets = [self.class contentInsets];
    size.width -= insets.left+insets.right;
    CGSize s = [self.flowlayout sizeThatFits:size resizeItems:YES];
    s.height += insets.top+insets.bottom;
    return s;
}
@end
